package com.nb.crawler.html;

import org.htmlcleaner.TagNode;
import org.htmlcleaner.XPatherException;

import java.util.ArrayList;
import java.util.List;

/**
 * 屏蔽实际的解析组件
 * <p/>
 * Created by cuibo on 15/1/14.
 */
public class Element {
    private TagNode node;

    public Element(TagNode node) {
        this.node = node;
    }

    public <T> List<T> each(String xpath, XPathCallback<T> callback) {
        List<T> result = new ArrayList<T>();
        try {
            Object[] children = node.evaluateXPath(xpath);

            //调用回调函数处理匹配到的节点
            if (callback != null) {
                for (Object child : children) {
                    Element element = new Element((TagNode) child);
                    T obj = callback.call(element, xpath);
                    result.add(obj);
                }
            }
        } catch (XPatherException e) {
            e.printStackTrace();
        }

        return result;
    }

    public String getName() {
        return node.getName();
    }

    public String getText() {
        return node.getText().toString().trim();
    }

    public String getAttribute(String name, String defaultValue) {
        String attribute = node.getAttributeByName(name);
        return attribute == null ? defaultValue : attribute;
    }

    public String getAttribute(String name) {
        return node.getAttributeByName(name);
    }

    public String getAttributeByXPath(String xpath, String name) {
        TagNode tagNode = getSingleNode(xpath);
        if (tagNode != null) {
            return tagNode.getAttributeByName(name);
        }
        return null;
    }

    public String getTextByXPath(String xpath) {
        TagNode tagNode = getSingleNode(xpath);
        if (tagNode != null) {
            return tagNode.getText().toString().trim();
        }
        return null;
    }

    private TagNode getSingleNode(String xpath) {
        try {
            Object[] objects = node.evaluateXPath(xpath);
            if (objects.length > 0) {
                return (TagNode) objects[0];
            }
        } catch (XPatherException e) {
            e.printStackTrace();
        }
        return null;
    }
}
